import { EmitType, Recordable } from '@/global'
import { Ref, unref, toRaw, ComputedRef } from 'vue'
import { FormActionType, FormSchema } from '../types/form'

interface UseFormActionContext {
  emit: EmitType
  getSchema: ComputedRef<FormSchema[]>
  formElRef: Ref<FormActionType>
  formModel: Recordable
  defaultValueRef: Ref<Recordable>
}
export function useFormEvents({
  emit,
  formElRef,
  formModel,
  getSchema,
  defaultValueRef
}: UseFormActionContext) {
  /**
   * 重置表单
   */
  async function resetFields(): Promise<void> {
    const formEl = unref(formElRef)
    if (!formEl) return

    Object.keys(formModel).forEach((key) => {
      formModel[key] = defaultValueRef.value[key]
    })
    clearValidate()
    emit('reset', toRaw(formModel))
  }
  /**
   * 获取表单值
   */
  function getFieldsValue(): Recordable {
    const formEl = unref(formElRef)
    if (!formEl) return {}
    return toRaw(unref(formModel))
  }
  /**
   * 表单赋值
   */
  async function setFieldsValue(values: Recordable): Promise<void> {
    const fields = unref(getSchema)
      .map((item) => item.field)
      .filter(Boolean)
    Object.keys(values).forEach((key) => {
      const hasKey = Reflect.has(values, key)
      if (hasKey && fields.includes(key)) {
        formModel[key] = values[key]
      }
    })
  }
  // 表单提交
  async function handleSubmit(e?: Event): Promise<void> {
    e && e.preventDefault()
    const formEl = unref(formElRef)
    if (!formEl) return
    try {
      const values = await validate()
      emit('submit', values)
    } catch (error) {
      // console.error('校验错误：' + error)
    }
  }
  /**
   * 表单校验
   */
  async function validate() {
    return await unref(formElRef)?.validate()
  }
  /**
   * 清除表单校验
   */
  async function clearValidate(name?: string | string[]) {
    await unref(formElRef)?.clearValidate(name)
  }
  return {
    getFieldsValue,
    setFieldsValue,
    resetFields,
    validate,
    clearValidate,
    handleSubmit
  }
}
